/**
 * Creater with IntelliJ IDEA.
 * Description:
 * User: 86152
 * Dae: 2022-07-28
 * Time: 15:10
 */
//自己实现阻塞队列
public class MyBlockingQueue {
    private int[] arr=new int[1000];
    private volatile int size=0;
    private int tail=0;
    private int head=0;
    public void put(int n) throws InterruptedException {
        synchronized (this) {
            //判断是否队满
            while (size == arr.length) {
                this.wait();
            }
            arr[tail] = n;
            size++;
            if(tail+1==arr.length) {
                tail=0;
            } else {
                tail++;
            }
            notifyAll();
        }
    }
    public int take() throws InterruptedException {
        int ret;
        synchronized (this) {
            while (size == 0) {
                this.wait();
            }
            ret=arr[head];
            if(head+1==arr.length) {
                head=0;
            } else {
                head++;
            }
            size--;
            notifyAll();
        }
        return ret;
    }
    public int getSize() {
        return size;
    }
}
class model {
    public static void main(String[] args) {
        MyBlockingQueue blockingQueue1 = new MyBlockingQueue();
        Thread customer = new Thread() {
            public void run() {
                while(true) {
                    synchronized (this) {
                        try {
                            int value = blockingQueue1.take();
                            System.out.println("消费！:"+value);
                            sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        };
        customer.start();
        Thread provider = new Thread() {
            public void run() {
                int n=1;
                while(true) {
                    synchronized (this) {
                        try {
                            blockingQueue1.put(n);
                            System.out.println("生产！:"+n);
                            n++;
//                            sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        };
        provider.start();
    }
}